const express = require('express')
const path = require('path')
const fs = require('fs')
const parser = require('body-parser')
const app = express()
const port = 3000

app.use(parser.urlencoded({ extended: false }))
app.use(parser.json())

const mysql = require('mysql')
const { error } = require('console')
//建立与数据库连接关系
const db = mysql.createPool({
    host: '127.0.0.1',//数据库ip地址
    user: 'root',
    password: '123456',
    database: 'luckindrinks'
})


//静态路由
app.use('/image', express.static(path.join(__dirname, "/images")))

// 主页json数据
app.get('/home', (req, res) => {
    fs.readFile(path.join(__dirname, "/JSON/home.json"), (err, dataStr) => {
        if (err) return console.log(err.message)
        res.type('json')
        res.send(dataStr)
    })
})
//所有饮品
app.get('/drink', (req, res) => {
    db.query('SELECT * from l_drink', (err, results) => {
        if (err) return console.log(err.message)
        res.send(results)
    })
})

//饮品的所有分类
app.get('/category', (req, res) => {
    db.query('SELECT * from L_category', (err, results) => {
        if (err) return console.log(err.message)
        res.send(results)
    })
})
//通过id查询饮品
app.get('/drink/:id', (req, res) => {
    var mz = req.params.id
    db.query('SELECT * from l_drink WHERE category_id = ?', [mz],
        (err, results) => {
            if (err) return error.message
            res.send(results)
        })
})

//菜单-超优惠
app.get('/drinks/top', (req, res) => {
    db.query('SELECT * from l_drink order by id asc limit 8 ',
        (err, results) => {
            if (err) return error.message
            res.send(results)
        })
})

//菜单-宝藏单品
app.get('/drinks/inBaby', (req, res) => {
    db.query('select * from l_drink where id in (9,17,27,29,30,31,32,34)',
        (err, results) => {
            if (err) return error.message
            res.send(results)
        })
})

//菜单-我的常点
app.get('/drinks/topUsuall', (req, res) => {
    db.query('SELECT * from l_drink order by id ASC limit 6 ',
        (err, results) => {
            if (err) return error.message
            res.send(results)
        })
})

//用户下单
app.post('/order', (req, res) => {
    db.query('INSERT INTO l_order (drinks_id,finalprice) VALUES (?,?)', [req.body.drinksList, req.body.price],
        (err, results) => {
            if (err) return console.log(err.message)
            res.send(results)
        })
})

//订单信息
app.get('/orders', (req, res) => {
    db.query("SELECT * from l_order ORDER BY id DESC",
        (err, results) => {
            if (err) return console.log(err.message)
            res.send(results)
        })
})
app.listen(port, () => console.log(`Example app listening http://127.0.0.1:${port}`))

